package com.nali.dal.mongo.ds;

import java.net.UnknownHostException;

import javax.annotation.PostConstruct;

import com.mongodb.DB;
import com.mongodb.Mongo;
import com.mongodb.MongoException;
import com.mongodb.MongoOptions;
import com.mongodb.ServerAddress;
import com.nali.dal.ds.IDataSource;

public class MongoDBDataSource implements IDataSource<DB> {
	private String host;
	private Integer port;
	private String db;
	private Integer connectionsPerHost;
	private Integer threadsAllowedToBlockForConnectionMultiplier;
	private Integer maxWaitTime;
	private Integer connectTimeout;
	private Integer socketTimeout;
	private Boolean autoConnectRetry;
	private Mongo mongo;
	
	@PostConstruct
	public void postConstruct() throws UnknownHostException, MongoException {
		MongoOptions options=new MongoOptions();
		if(connectionsPerHost!=null) {
			options.connectionsPerHost=connectionsPerHost;
		}
		if(threadsAllowedToBlockForConnectionMultiplier!=null) {
			options.threadsAllowedToBlockForConnectionMultiplier=threadsAllowedToBlockForConnectionMultiplier;
		}
		if(maxWaitTime!=null) {
			options.maxWaitTime=maxWaitTime;
		}
		if(connectTimeout!=null) {
			options.connectTimeout=connectTimeout;
		}
		if(socketTimeout!=null) {
			options.socketTimeout=socketTimeout;
		}
		if(autoConnectRetry!=null) {
			options.autoConnectRetry=autoConnectRetry;
		}
		ServerAddress serverAddress;
		if(port!=null) {
			serverAddress = new ServerAddress(host, port);
		} else {
			serverAddress = new ServerAddress(host);
		}
		mongo = new Mongo(serverAddress, options);
	}

	public void setHost(String host) {
		this.host = host;
	}

	public void setPort(int port) {
		this.port = port;
	}

	public void setDb(String db) {
		this.db = db;
	}

	public void setConnectionsPerHost(Integer connectionsPerHost) {
		this.connectionsPerHost = connectionsPerHost;
	}

	public void setThreadsAllowedToBlockForConnectionMultiplier(Integer threadsAllowedToBlockForConnectionMultiplier) {
		this.threadsAllowedToBlockForConnectionMultiplier = threadsAllowedToBlockForConnectionMultiplier;
	}

	public void setMaxWaitTime(Integer maxWaitTime) {
		this.maxWaitTime = maxWaitTime;
	}

	public void setConnectTimeout(Integer connectTimeout) {
		this.connectTimeout = connectTimeout;
	}

	public void setSocketTimeout(Integer socketTimeout) {
		this.socketTimeout = socketTimeout;
	}

	public void setAutoConnectRetry(Boolean autoConnectRetry) {
		this.autoConnectRetry = autoConnectRetry;
	}

	@Override
	public DB getConnection() {
		return mongo.getDB(db);
	}

}
